package com;
//MySQL查询
import com.mysql.cj.protocol.Resultset;
import com.mysql.cj.x.protobuf.MysqlxCrud;

import java.sql.*;

public class Demo1 {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            //1.加载驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获得链接
            String userName="root";
            String passWord="123456";
            String url="jdbc:mysql://localhost:3306/yhp2?serverTimezone=UTC";
            connection = DriverManager.getConnection(url,userName,passWord);
            //3.定义sql,创建状态通道(进行sql语句的发送)
            statement = connection.createStatement();
            resultSet = statement.executeQuery("select* from emp1");//executeQuery(sql) 执行查询
            //executeUpdate(sql) 执行增删改 返回受影响的行数
            //int result = statement.executeUpdate("insert into emp1(ename,hiredate,sal) values('小王','2020-1-1','2000')");
            //if(result>0){
            //    System.out.println("执行成功");
            //}else{
            //    System.out.println("执行失败");
            //}
            //如果只增删改 不查询操作的话 程序中所有关于 resultSet 的成分都可以删去
            //取出结果集信息
            while (resultSet.next()){//判断是否有下一条数据
                //取出数据 resultSet.getxxx();  xxx表示数据类型
                System.out.println("姓名："+resultSet.getString("ename")+"工资："+resultSet.getInt("sal")
                +" 雇佣日期："+resultSet.getDate("hiredate"));
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            try {
                if (resultSet != null){//判断之前是否连接上
                    resultSet.close();
                }
                if(statement != null){
                    statement.close();
                }
                if (connection != null){
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}
